"""
图片处理模块
负责图片下载、预处理和格式转换
"""

import io
import httpx
from PIL import Image
from fastapi import HTTPException
import logging

logger = logging.getLogger(__name__)

class ImageProcessor:
    """图片处理器"""

    def __init__(self, config: dict):
        self.config = config

    async def download_image(self, image_url: str) -> bytes:
        """下载网络图片"""
        try:
            async with httpx.AsyncClient(timeout=self.config['image_service']['timeout']) as client:
                response = await client.get(image_url)
                response.raise_for_status()
                return response.content
        except Exception as e:
            logger.error(f"下载图片失败: {str(e)}")
            raise HTTPException(status_code=400, detail=f"下载图片失败: {str(e)}")

    def process_image(self, image_bytes: bytes) -> bytes:
        """
        统一处理图片：转换格式并调整大小
        """
        try:
            image = Image.open(io.BytesIO(image_bytes))

            # 转换WebP等格式为JPG
            if image.format == 'WEBP' or image.mode == 'RGBA':
                if image.mode == 'RGBA':
                    background = Image.new('RGB', image.size, (255, 255, 255))
                    background.paste(image, mask=image.split()[3])
                    image = background
                else:
                    image = image.convert('RGB')

            # 调整图片大小以优化性能
            max_size = self.config['image_service'].get('resize_max_size', 1024)
            if image.width > max_size or image.height > max_size:
                image.thumbnail((max_size, max_size))

            buffer = io.BytesIO()
            image.save(buffer, format="JPEG")
            return buffer.getvalue()
        except Exception as e:
            logger.error(f"图片处理失败 (format conversion/resize): {str(e)}")
            raise HTTPException(status_code=400, detail=f"图片处理失败: {str(e)}")

    def validate_image_file(self, file_content: bytes, filename: str = None) -> bool:
        """验证图片文件"""
        try:
            Image.open(io.BytesIO(file_content)).verify()
            return True
        except Exception as e:
            logger.error(f"图片文件验证失败: {str(e)}")
            return False
